<template>
	<view class="order-pages">
		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" title="商城订单" color="#ffffff" leftIcon="icon-left"
			:backgroundColor="primaryColor">
		</uni-nav-bar>
		<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
		<fixed :top="configInfo.navBarHeight">
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<fixed>
				<!-- #endif -->
				<tab @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1" :activeColor="primaryColor"
					:width="100/tabList.length + '%'" height="100rpx"></tab>
				<view class="b-1px-b"></view>
			</fixed>

			<view @tap.stop="goDetail(index,'detail')"
				class="item-child mt-md ml-md mr-md pd-lg fill-base radius-16 rel" v-for="(item,index) in dataList"
				:key="index">
				<view class="flex-between pb-lg b-1px-b">
					<view class="f-paragraph c-title max-450 ellipsis"
						@tap.stop="$util.goUrl({openType:'copy',url:item.order_no})">订单号：{{item.order_no}}
					</view>
					<!-- // pay_type 1待支付，2待服务，3技-师接单，4技-师出发，5技-师到达，6服务中，7服务完成 -->
					<view class="f-caption text-bold"
						:style="{color:item.status==0?primaryColor: [0,1].includes(item.status)?subColor: item.status == 2 ? '#11C95E' : '#333'}">
						{{statusType[item.status]}}
					</view>
				</view>
				<view class="flex-center mt-lg">
					<!-- #ifdef H5 -->
					<view class="cover radius-16">
						<view class="h5-image cover radius-16"
							:style="{ backgroundImage : `url('${item.good_cover}')`}">
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<image mode="aspectFill" class="cover radius-16" :src="item.good_cover"></image>
					<!-- #endif -->
					<view class="flex-1 ml-md">
						<view class="flex-between">
							<view class="f-mini-title c-title text-bold max-400 ellipsis">
								{{item.good_name}}
							</view>
							<view class="f-desc c-desc">x{{item.number}}</view>
						</view>
						<!-- <view class="flex-y-center f-caption c-caption">预约时间<view class="ml-md">{{item.start_time}}
							</view>
						</view> -->
						<view class="flex-y-center f-caption c-caption">总计：
							<view class="flex-y-baseline c-warning text-bold">¥
								<view class="f-title">{{item.pay_price}}</view>
							</view>
						</view>
					</view>
				</view>
				<view class="flex-between pt-lg">
					<view></view>
					<view class="flex-warp">
						<!-- 待支付 -->
						<block v-if="item.status == 0">
							<button @tap.stop="toAction(index, 'cancel')" class="clear-btn order">取消订单</button>
							<button @tap.stop="toPay(index)" class="clear-btn order"
								:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">去支付</button>
						</block>
						<!-- 支付超时 -->
						<block v-if="item.status == -1 || item.status == -3">
							<button @tap.stop="toAction(index, 'delete')" class="clear-btn order">删除</button>
						</block>
						
						<!-- 虚拟订单完成 -->
						<block v-if="item.status == 1 && item.type == 2">
							<button @tap.stop="toAction(index, 'complete')" class="clear-btn order">完成</button>
						</block>
						
						<!-- 确认收货 -->
						<block v-if="item.status == 2 && item.type == 1">
							<button @tap.stop="toAction(index, 'complete')" class="clear-btn order">确认收货</button>
						</block>
						
						<!-- 已完成 -->
						<!-- <block v-if="item.express_id && item.status == 2">
							<button @tap.stop="toAgain(index)" class="clear-btn order"
								:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">再来一单</button>
						</block> -->
					</view>
				</view>
			</view>

			<load-more :noMore="page*limit < total &&dataList.length>0" :loading="loading"
				v-if="loading">
			</load-more>
			<abnor v-if="!loading&&dataList.length<=0"></abnor>
			<view class="space-footer"></view>

			<common-popup @confirm="confirmCancel" ref="cancel" type="CANCEL_ORDER" :info="popupInfo"> </common-popup>
			<common-popup @confirm="confirmDel" ref="delete" type="DELETE_ORDER" :info="popupInfo"></common-popup>
			
			

			<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
			<!-- <tabbar :cur="4"></tabbar> -->
			<!-- <change-user-type></change-user-type> -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	// import tabbar from "@/components/tabbar.vue"
	export default {
		components: {
			// tabbar
		},
		data() {
			return {
				options: {},
				navTitle: '',
				
				activeIndex: 0,
				tabList: [{
					title: '全部',
					id: 'all'
				}, {
					title: '待支付',
					id: 0,
					// number: 10
				}, {
					title: '待发货',
					id: 1
				}, {
					title: '待收货',
					id: 2
				}, {
					title: '已完成',
					id: 3
				}],
				
				statusType: {
					'-1': '已取消',
					0: '待支付',
					1: '已支付',
					2: '待收货',
					3: '已完成',
				},
				loading: true,
				popupInfo: {},
				lockTap: false,
				
				
				page: 1,
				status: 'all',
				total: 0,
				limit: 10,
				
				dataList: []
			}
		},
		computed: mapState({
			// activeIndex: state => state.order.activeIndex,
			// tabList: state => state.order.tabList,
			// param: state => state.order.param,
			// list: state => state.order.list,
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			userInfo: state => state.user.userInfo,
		}),
		async onLoad(options) {
			let {
				tab = 0
			} = options
			// this.updateOrderItem({
			// 	key: 'activeIndex',
			// 	val: tab
			// })
			
			this.activeIndex = tab
			
			// 支付后需刷新页面
			await this.initIndex()
			// let {
			// 	tabBar
			// } = this.configInfo
			// let ind = tabBar.findIndex(item => {
			// 	return item.id == 4
			// })
			// let navTitle = ind == -1 ? '订单' : tabBar[ind].name
			// this.navTitle = navTitle
			// // #ifdef H5
			// uni.setNavigationBarTitle({
			// 	title: navTitle
			// })
			// // #endif
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initRefresh();
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if ( ( (this.page * this.limit) >= this.total ) || this.loading) return;
			this.loading = true;
			this.page += 1
			this.getList();
		},
		methods: {
			...mapActions(['getConfigInfo']),
			// ...mapMutations(['updateOrderItem']),
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.$jweixin.wxReady(() => {
						this.$jweixin.hideOptionMenu()
					})
				}
				// #endif
				if (!this.configInfo.id || refresh) {
					await this.getConfigInfo()
				}
				
				
				this.page = 1
				this.total = 0
				this.dataList = []
				await this.getList(1)
			},
			initRefresh() {
				this.initIndex(true)
			},
			async getList(page = 0) {
				await this.$api.order.goodOrderList(
				{
					page: this.page,
					limit: this.limit,
					status: this.tabList[this.activeIndex].id
				})
				.then(response => {
					console.log(response)
					this.dataList = this.dataList.concat(response.data)
					this.total = response.total
				})
				.catch(() => uni.hideLoading())
				.finally(() => {
					this.loading = false
					uni.hideLoading()
				})
			},
			
			handerTabChange(index) {
				// console.log(index)
				this.activeIndex = index
				uni.pageScrollTo({
					scrollTop: 0
				})
				this.$util.showLoading()
				
				this.page = 1
				this.total = 0
				this.dataList = []
				
				this.getList(1)
			},
			
			// 取消/删除订单
			async toAction(index, type) {
				
				if(type == 'complete') {
					return this.onComplete(index)
				}
				
				let {
					id,
					order_no,
					status,
					good_cover
				} = this.dataList[index]
				// console.log(good_cover)
				this.popupInfo = {
					id,
					name: `系统单号：${order_no}`,
					good_cover,
					index,
				}
				// let refs_key = status == 0 ? 'cancel_item' : 'del_item'
				this.$refs[type].open()
			},
			
			
			async onComplete(index) {
				let that = this
				await uni.showModal({
					title: "温馨提示",
					content:"是否确定订单已完成",
					async success(res) {
						if(res.confirm) {
							await that.$api.order.goodOrderComplete({
								id: that.dataList[index].id
							})
							if (that.activeIndex == 0) {
								that.dataList[index].status = 3
							}
							that.$util.showToast({
								title: `操作成功`
							})
						}
					}
				})
			},
			
			// 确认：取消订单
			async confirmCancel() {
				let {
					id,
					index,
				} = this.popupInfo
				await this.$api.order.goodOrderCancel({
					id
				})
				if (this.activeIndex == 0) {
					this.dataList[index].status = -1
				} else {
					this.dataList.splice(index, 1)
				}
				this.$util.showToast({
					title: `取消成功`
				})
				this.$refs.cancel.close()
			},
			// 确认：删除订单
			async confirmDel() {
				let {
					id,
					index,
				} = this.popupInfo
				await this.$api.order.goodOrderDele({
					id
				})
				this.dataList.splice(index, 1)
				this.$util.showToast({
					title: `删除成功`
				})
				this.$refs.delete.close()
			},
			// 去支付
			async toPay(index) {
				if (this.lockTap) return;
				this.lockTap = true;
				this.$util.showLoading()
				let {
					id,
					pay_type
				} = this.dataList[index]

				try {
					let {
						pay_list
					} = await this.$api.order.goodOrderRePay({
						id
					})
					this.$util.hideAll()
					if (pay_list) {
						if (pay_type == 3) {
							pay_list = {
								orderInfo: pay_list,
								provider: 'alipay'
							}
						}

						// #ifdef H5

						if (pay_type == 3) {
							pay_list = Object.assign({}, pay_list, {
								order_id: id,
								page_url: `/technician/pages/shop/order?tab=2`
							})
							this.updateOrderItem({
								key: 'alipayOrderParams',
								val: pay_list
							})
							this.$util.goUrl({
								url: '/user/pages/alipay-result'
							})
							this.lockTap = false
							setTimeout(() => {
								this.initRefresh()
							}, 3000)
							return
						}
						// #endif

						try {
							await this.$util.pay(pay_list)
							this.$util.showToast({
								title: `支付成功`
							})
							if (this.activeIndex == 0) {
								this.dataList[index].status = 2
							} else {
								this.dataList.splice(index, 1)
							}
							this.lockTap = false;
						} catch (e) {
							this.$util.showToast({
								title: `支付失败`
							})
							this.lockTap = false;
							return
						}
					}
					
					
					// 余额支付/零元支付
					this.$util.showToast({
						title: `支付成功`
					})
					this.lockTap = false
					setTimeout(() => {
						this.initRefresh()
						// this.lockTap = false
						// this.$util.goUrl({
						// 	url: '/technician/pages/shop/order?tab=2',
						// 	openType: `redirectTo`
						// })
					}, 1000)
					
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			
			// 订单详情/申请退款/去评价
			goDetail(index, page) {
				let {
					id
				} = this.dataList[index]
				let url = `/technician/pages/shop/orderDetail?id=${id}`
				this.$util.goUrl({
					url
				})
			},
			// 再来一单
			async toAgain(index) {
				let {
					id: order_id,
					coach_id
				} = this.dataList[index]
				await this.$api.order.onceMoreOrder({
					order_id
				})
				this.$util.goUrl({
					url: `/user/pages/order?id=${coach_id}`
				})
			}
		}
	}
</script>


<style lang="scss">
</style>